package swu.cart;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import swu.commodity.Commodity;
import swu.commodity.CommodityRepo;
import swu.commodity.CommodityService;

import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/client/cart/*")
public class CartOperator extends HttpServlet
{
    CommodityService commodityService = null;
    CartService cartService = null;
    protected SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-mm-dd");

    @Override
    public void init(ServletConfig config) throws ServletException
    {
        CommodityRepo commodityRepo = new CommodityRepo();
        CartRepo cartRepo = new CartRepo();
        cartService = new CartService();
        commodityService = new CommodityService();
        cartService.setCartRepo(cartRepo);
        commodityService.setRepo(commodityRepo);
        System.out.println("初始化成功！");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        doPost(req,resp);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        try
        {
            this.methodRoute(request, response);
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException, SQLException, JsonProcessingException
    {
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);

        if (method.equals("AddToCart"))
        {
            this.addTocart(request, response);
        }
        else if (method.equals("RemoveFromCart"))
        {
            this.removeFromCart(request, response);
        }
        else if (method.equals("GetCart"))
        {
            this.getCart(request, response);
        }
    }

    public void addTocart(HttpServletRequest request,HttpServletResponse response) throws SQLException
    {
        int id = Integer.parseInt(request.getParameter("id"));
        HttpSession session = request.getSession(true);
        Commodity commodity = commodityService.getCommodityById(id);

        List<Commodity> cart = (List<Commodity>) session.getAttribute("cart");

        if (cart == null)
        {
            cart = new ArrayList<>();
            session.setAttribute("cart", cart);
        }

        if(cartService.isCommodityExists(cart,id))
        {
            return;
        }
        else
        {
            cartService.addToCartById(cart,id);
        }

    }

    public void removeFromCart(HttpServletRequest request, HttpServletResponse response) throws SQLException
    {
        String productId = request.getParameter("id");
        int id = Integer.parseInt(productId);
        Commodity commodity = commodityService.getCommodityById(id);

        HttpSession session = request.getSession(true);
        List<Commodity> cart = (List<Commodity>) session.getAttribute("cart");

        cartService.deleteFromCartById(cart,id);

    }

    public void getCart(HttpServletRequest request,HttpServletResponse response) throws JsonProcessingException
    {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");

        List<Commodity> cart = (List<Commodity>) session.getAttribute("cart");

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(dateFormatter);
        String jsonString = objectMapper.writeValueAsString(cart);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try
        {
            response.getWriter().write(jsonString);
        } catch (IOException e)
        {
            throw new RuntimeException(e);
        }

    }
}

